package edu.berkeley.cs160.GroupC;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

public class IntensityService extends Service {
	private static final String TAG = "edu.berkeley.cs160.GroupC.IntensityService";	
	
	private WorkoutMusicApplication app = (WorkoutMusicApplication)getApplication();;
	
	private SensorManager mSensorManager;
    private Sensor mSensor;
    private StepDetector mStepDetector;
    // private StepBuzzer mStepBuzzer; // used for debugging
    private StepNotifier mStepNotifier;
    private PaceNotifier mPaceNotifier;
    private PowerManager.WakeLock wakeLock;
    private NotificationManager mNM;    
    
    private int mSteps;
    private int mPace;

	protected boolean wakeAggressively = false;    
    
    
    public class StepBinder extends Binder {
    	IntensityService getService(){
    		return IntensityService.this;
    	}
    }
    private final IBinder mBinder = new StepBinder();
    @Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
    
    public interface ICallback {
        public void stepsChanged(int value);
        public void paceChanged(int value);
    }
    
    private ICallback mCallback;

    public void registerCallback(ICallback cb) {
        mCallback = cb;
    }
    
    
    @Override
    public void onCreate() {
        Log.i(TAG, "[SERVICE] onCreate");
        super.onCreate();
        
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        showNotification();
        acquireWakeLock();
        mStepDetector = new StepDetector();
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        registerDetector();
        
        
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
        
        mStepNotifier = new StepNotifier();
        mStepNotifier.setSteps(0);
        mStepNotifier.addListener(mStepListener);
        mStepDetector.addStepListener(mStepNotifier);
        
        mPaceNotifier = new PaceNotifier();
        mPaceNotifier.setPace(0);
        mPaceNotifier.addListener(mPaceListener);
        mStepDetector.addStepListener(mPaceNotifier);
        
        
        Toast.makeText(this, "Intensity Detection Started!!", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "[SERVICE] onStart");
        super.onStart(intent, startId);
    }
    

    @Override
    public void onDestroy() {
        Log.i(TAG, "[SERVICE] onDestroy");

        // Unregister our receiver.
        unregisterReceiver(mReceiver);
        unregisterDetector();
        mNM.cancel(R.string.app_name);
        
        wakeLock.release();
        
        super.onDestroy();
        
        // Stop detecting
        mSensorManager.unregisterListener(mStepDetector);

        // Tell the user we stopped.
        Toast.makeText(this, "Intensity Detection Stopped", Toast.LENGTH_SHORT).show();
    }

    
    private StepNotifier.Listener mStepListener = new StepNotifier.Listener() {
        public void stepsChanged(int value) {
            mSteps = value;
            passValue();
        }
        public void passValue() {
            if (mCallback != null) {
                mCallback.stepsChanged(mSteps);
            }
        }
    };
    
    private PaceNotifier.Listener mPaceListener = new PaceNotifier.Listener() {
        public void paceChanged(int value) {
            mPace = value;
            passValue();
        }
        public void passValue() {
            if (mCallback != null) {
                mCallback.paceChanged(mPace);
            }
        }
    };
    
    
    
    public void reloadSettings() {
        
        if (mStepDetector != null) { 
            mStepDetector.setSensitivity(WorkoutMusicApplication.SENSITIVITY);
        }
        if (mStepNotifier    != null) mStepNotifier.reloadSettings();
        if (mPaceNotifier     != null) mPaceNotifier.reloadSettings();
    }
    
    public void resetValues() {
        mStepNotifier.setSteps(0);
        mPaceNotifier.setPace(0);
    }
    
    private void registerDetector() {
        mSensor = mSensorManager.getDefaultSensor(
                Sensor.TYPE_ACCELEROMETER /*| 
                Sensor.TYPE_MAGNETIC_FIELD | 
                Sensor.TYPE_ORIENTATION*/);
        mSensorManager.registerListener(mStepDetector, mSensor, SensorManager.SENSOR_DELAY_UI);
		
	}
	private void unregisterDetector() {
		mSensorManager.unregisterListener(mStepDetector);
		
	}    

	private void showNotification() {
        CharSequence text = getText(R.string.app_name);
        Notification notification = new Notification(R.drawable.rabbit3, null,
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        Intent playSongIntent = new Intent();
        playSongIntent.setComponent(new ComponentName(this, PlaySongs.class));
        playSongIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                playSongIntent, 0);
        notification.setLatestEventInfo(this, text,
                getText(R.string.notification_subtitle), contentIntent);
        
        mNM.notify(R.string.app_name, notification);
	}








	// BroadcastReceiver for handling ACTION_SCREEN_OFF.
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Check action just to be on the safe side.
            /*
        	if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                // Unregisters the listener and registers it again.
                IntensityService.this.unregisterDetector();
                IntensityService.this.registerDetector();
                if (!wakeAggressively ) {
                    wakeLock.release();
                    acquireWakeLock();
                }
            }
            */
        }
    };

    private void acquireWakeLock() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        int wakeFlags;
        if (!wakeAggressively) {
            wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
        }
        else {
            wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
        }
        wakeLock = pm.newWakeLock(wakeFlags, TAG);
        wakeLock.acquire();
        
    }


}












